# -*- coding: utf-8 -*-
from django.contrib.auth import authenticate, login, logout
 
#from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist

from bigmama.BabyMgr.models import Baby
from bigmama.BabyMgr.models import HeightHistory 
from bigmama.BabyMgr.models import WeightHistory
from bigmama.BabyMgr.models import BabyFoodHistory
from bigmama.BabyMgr.models import ChildcareDairy
from bigmama.BabyMgr.models import PhotoHistory

# Create your views here.
def main_page(request):
    return render_to_response('main_page.html', {'user':request.user})    

def login_main_page(request):
    return render_to_response('login_main_page.html', {'user':request.user})

def select_memo_page(request):
    if not request.user.is_authenticated():
        return HttpResponse("[Error] select_memo_page : User didn't login : % s" % str(request.user))

    form_name = request.POST['select_baby']   
    selected_baby = Baby.objects.get(name = form_name) 
    memo_list = ChildcareDairy.objects.filter(baby = selected_baby)   
    
    return render_to_response('memolog_history_page.html', {'user':request.user, 'memo':memo_list, 'baby':form_name})

def memolog_page(request):
    if not request.user.is_authenticated():
        return HttpResponse("[Error] memolog_page : User didn't login : % s" % str(request.user))
    babies = Baby.objects.filter(parent = request.user)  
#    memo_list = ChildcareDairy.objects.filter(baby = babies.name)
    return render_to_response('memolog_page.html', {'user':request.user, 'babies':babies})

def photolog_page(request):
    if not request.user.is_authenticated():
        return HttpResponse("[Error] photolog_page : User didn't login : % s" % str(request.user))
    
    babies = Baby.objects.filter(parent = request.user)    
    return render_to_response('photolog_page.html', {'user':request.user, 'babies':babies})

def select_photo_page(request):
    if not request.user.is_authenticated():
        return HttpResponse("[Error] select_photo_page : User didn't login : % s" % str(request.user))

    form_name = request.POST['select_baby']   
    selected_baby = Baby.objects.get(name = form_name) 
    photo_list = PhotoHistory.objects.filter(baby = selected_baby)   
    
    return render_to_response('photolog_history_page.html', {'user':request.user, 'photo':photo_list, 'baby':form_name})    

def select_build_page(request):
    if not request.user.is_authenticated():
        return HttpResponse("[Error] select_build_page : User didn't login : % s" % str(request.user))
    msg = ''
    _name = request.POST['action']    
 
    babies = Baby.objects.get(name = _name)
    height = HeightHistory.objects.filter(baby = babies)       
    weight = WeightHistory.objects.filter(baby = babies)

    height_log = ''
    date_log = ''
    index = 0
    
    count = len(height)
    for line in height:
        index = index + 1
        height_log = height_log + str(line.height)        
        date = str(line.record_date)
        date_log = date_log.strip() + date.strip()       

        if index != count:
            height_log = height_log + ','
            date_log = date_log.strip() + '|'
            
    height_chart = 'img src=http://chart.apis.google.com/chart?cht=lc&chs=400x200&chd=t:'
    height_chart = height_chart + height_log    
    height_chart = height_chart + '&chds=0,100'
    height_chart = height_chart + '&chl='
    height_chart = height_chart + date_log    
    
    weight_log = ''
    date_log = ''
    index = 0
    
    count = len(weight)
    for line in weight:
        index = index + 1
        weight_log = weight_log + str(line.weight)
        date_log = date_log.strip() + str(line.record_date).strip()
        if index != count:
            weight_log = weight_log + ','
            date_log = date_log.strip() + '|'
            
    weight_chart = 'img src=http://chart.apis.google.com/chart?cht=lc&chs=400x200&chd=t:'
    weight_chart = weight_chart + weight_log
    weight_chart = weight_chart + '&chds=0,20'
    weight_chart = weight_chart + '&chl=' + date_log    

#    weight_chart = 'img src=http://chart.apis.google.com/chart?chs=400x200&chd=t:60,40&cht=lc&chl=몸무게 성장 그래프'

    return render_to_response('buildlog_history_page.html', {'user':request.user, 'height':height, 'weight' : weight, 'height_chart' : height_chart, 'weight_chart' : weight_chart})
    
#    return HttpResponse(msg)
#    if request.method == 'GET':
#        msg = msg + str(request.GET.values()) + '|GET|' + '\n'
#        list = request.GET.lists()
#        for line in list:
#            msg = msg + str(line) + '\n'            
#        msg = msg + '|GET|' + '\n'    
#    elif request.method == 'POST':
#        msg = msg + str(request.GET.values()) + '|POST|' + '\n'
#        list = request.POST.lists()
#        for line in list:
#            msg = msg + str(line) + '\n\n'            
#        msg = msg + '|POST|'+ '\n'            
#    
#    return HttpResponse(msg)
    
    return render_to_response('buildlog_history_page.html', {'babies':babies})    

def buildlog_page(request):
    if not request.user.is_authenticated():
        return HttpResponse("[Error] register_baby_page : User didn't login : % s" % str(request.user))
    
    babies = Baby.objects.filter(parent = request.user)  
#  
#    height_chart = 'img src=http://chart.apis.google.com/chart?chs=400x200&chd=t:60,40&cht=p3&chl=Hello|World'
#    weight_chart = 'img src=http://chart.apis.google.com/chart?chs=400x200&chd=t:60,40&cht=p3&chl=Hello|World'    
   
    return render_to_response('buildlog_page.html', {'babies':babies, 'user':request.user})    
    
#    msg = ''
#    for line in babies:
#        msg = msg + str(line) + '\n'
#    
#    return HttpResponse(msg)
#
#    
#    
#    msg = 'img src='
#    msg = msg + 'http://chart.apis.google.com/chart?cht=lc&chs=400x200'    
#    msg = msg + '&chd=t:81.5,82.7,34.4,45.2,50.4,38.3,69.5,45,41.2'
#    msg = msg + '&chl=5|6|7|8|9|10|11|12|13&chxt=y&chtt=visitors/10%20(march,%202008)&chco=ff00ff'
#    
#    height = 'img src=http://chart.apis.google.com/chart?chs=400x200&chd=t:60,40&cht=p3&chl=Hello|World'
#    weight = 'img src=http://chart.apis.google.com/chart?chs=400x200&chd=t:60,40&cht=p3&chl=Hello|World'    
#    return render_to_response('buildlog_page.html', {'height':msg, 'weight' : weight})
#    pass

#def login_page(request):    
#    username = request.POST['username']
#    password = request.POST['password']
#    user = authenticate(username=username, password=password)
#    if user is not None:
#        if user.is_active:
#            login(request, user)
#            return HttpResponse("You provided a correct username and password!")            
#        else:
#            return HttpResponse("Your account has been disabled!")            
#    else:
#        return HttpResponse("Your username and password were incorrect.")
#       
#def logout_page(request):    
#    logout(request)
#    # Redirect to a success page.
#    return HttpResponseRedirect('/')
#    
#def redirect_login_page(request):    
#    if not request.user.is_authenticated():
#        return HttpResponseRedirect('/login/?next=%s' % request.path)

def dummy(request):
    msg = ''
    msg = msg + str(request.user) + '|' + '\n'
    msg = msg + request.path + '|' + '\n'
    msg = msg + request.method + '|' + '\n'
    msg = msg + str(request.encoding) + '|'  + '\n'
    msg = msg + str(request.META) + '|'  + '\n'    
    msg = msg + str(request.session) + '|' + '\n'  
    
    list = []
    
    msg = msg + str(request.user) + '|' + '\n'
    
    if request.user.is_authenticated():        
        msg = msg + "is authenticated" + '\n'
    else:
        msg = msg + "is not authenticated\n" + '\n'    
    if request.method == 'GET':
        msg = msg + str(request.GET.values()) + '|GET|' + '\n'
#        list = request.GET.lists()
#        for line in list:
#            msg = msg + line + '\n'            
#        msg = msg + '|GET|' + '\n'    
    elif request.method == 'POST':
        msg = msg + str(request.GET.values()) + '|POST|' + '\n'
#        list = request.POST.lists()
#        for line in list:
#            msg = msg + line + '\n\n'            
#        msg = msg + '|POST|'+ '\n'            
    return HttpResponse(msg)

def session_test(request):
    if request.GET.has_key("data"):
        request.session['data'] = request.GET['data']
    if not request.session.has_key('data'):
        return HttpResponse(u"There is no session data")
    else:
        return HttpResponse(u"Session data : %s" % request.session['data'])

def register_user_page(request):
    if request.method != 'POST':
        return HttpResponse("[Error] register_user_page : It only permits POST messages")
    
    _username = request.POST['username']
    _password1 = request.POST['password1']
    _password2 = request.POST['password2']
    _email = request.POST['email']

    if _password1 != _password2:
        return HttpResponse("[Error] register_user_page : password 1 and password 2 are not equal! ")
    
    # Error handling code will be implemented
    try:
        User.objects.get(username = _username)
    except ObjectDoesNotExist: 
        user = User.objects.create_user(
        username = _username,
        password = _password1,
        email = _email)          
        return HttpResponse("[Success] register_user_page : The %s is registered! " % _username)
    
    return HttpResponse("[Error] register_user_page : The %s is already registered! " % _username) 

def login_page(request):
    if request.method != 'POST':
        return HttpResponse("[Error] login_page : It only permits POST messages")    
    _username = request.POST['username']
    _password = request.POST['password']

    user = authenticate(username = _username, password = _password)
    if user is not None:
        if user.is_active:
            login(request, user)
            return HttpResponse("[Success] login_page : The %s user is succesfully login!" % _username)            
        else:
            return HttpResponse("[Error] login_page : The %s account has been disabled!" % _username)            
    else:
        return HttpResponse("[Error] login_page : The username and password were incorrect.")
    
def logout_page(request):
#    if not request.user.is_authenticated():        
#        msg = ''
#        msg = msg + str(request.META) + '|'  + '\n'    
#        msg = msg + str(request.session) + '|' + '\n'
##        return HttpResponse("[Error] logout_page : User didn't login : % s" % str(request.user))
#        return HttpResponse(msg)    
    logout(request)
    return HttpResponse("[Success] logout_page : The user is succesfully logout!")

def register_baby_page(request):    
    if request.method != 'POST':
        return HttpResponse("[Error] register_baby_page : It only permits POST messages")    
#    if not request.user.is_authenticated():
#        return HttpResponse("[Error] register_baby_page : User didn't login : % s" % str(request.user))
        
    _parent = request.POST['parent']
    _name = request.POST['name']
    _birth = request.POST['birth']
    _gender = request.POST['gender']

    try:     
        user = User.objects.get(username = _parent)
    except ObjectDoesNotExist:
        return HttpResponse("[Error] register_baby_page : The %s is not registered parent! " % _parent)
  
    new_baby = Baby(parent = user, name = _name, birth = _birth, gender = _gender)
    new_baby.save()

    return HttpResponse("[Success] register_baby_page : The %s is succesfully registerd!" % _name)

def logging_height_page(request):
    if request.method != 'POST':
        return HttpResponse("[Error] logging_height_page : It only permits POST messages")
    
    _baby = request.POST['baby']
    _date = request.POST['record_date']
    _height = request.POST['height']
    
    try:
        babyInstance = Baby.objects.get(name = _baby)
    except ObjectDoesNotExist:
        return HttpResponse("[Error] logging_height_page : The %s baby isn't exist! " % _baby)
    
    height_log = HeightHistory(baby = babyInstance, record_date = _date, height = _height)
    height_log.save()
    
    return HttpResponse("[Success] logging_height_page : The %s baby's height is successfully inserted!" % _baby)

def logging_weight_page(request):
    if request.method != 'POST':
        return HttpResponse("[Error] logging_weight_page : It only permits POST messages")
    
    _baby = request.POST['baby']
    _date = request.POST['record_date']
    _weight = request.POST['weight']
    
    try:
        babyInstance = Baby.objects.get(name = _baby)
    except ObjectDoesNotExist:
        return HttpResponse("[Error] logging_weight_page : The %s baby isn't exist! " % _baby)
    
    weight_log = WeightHistory(baby = babyInstance, record_date = _date, weight = _weight)
    weight_log.save()
    
    return HttpResponse("[Success] logging_weight_page : The %s baby's weight is successfully inserted!" % _baby)   

def logging_menu_page(request):
    if request.method != 'POST':
        return HttpResponse("[Error] logging_menu_page : It only permits POST messages")
    
    _baby = request.POST['baby']
    _date = request.POST['record_date']
    _menu = request.POST['menu']
    _capacity = request.POST['capacity']
    
    try:
        babyInstance = Baby.objects.get(name = _baby)
    except ObjectDoesNotExist:
        return HttpResponse("[Error] logging_menu_page : The %s baby isn't exist! " % _baby)
    
    menu_log = BabyFoodHistory(baby = babyInstance, record_date = _date, menu = _menu, capacity = _capacity)
    menu_log.save()
        
    return HttpResponse("[Success] logging_menu_page : The %s baby's menu is successfully inserted!" % _baby)   

def logging_dairy_page(request):
    if request.method != 'POST':
        return HttpResponse("[Error] logging_dairy_page : It only permits POST messages")
    
    _baby = request.POST['baby']
    _date = request.POST['record_date']
    _memo = request.POST['memo']
    
    try:
        babyInstance = Baby.objects.get(name = _baby)
    except ObjectDoesNotExist:
        return HttpResponse("[Error] logging_dairy_page : The %s baby isn't exist! " % _baby)
    
    dairy_log = ChildcareDairy(baby = babyInstance, record_date = _date, memo = _memo)
    dairy_log.save()
    
    return HttpResponse("[Success] logging_dairy_page : The %s baby's dairy is successfully inserted!" % _baby)

# FIX_ME
# Image and Voice file upload code will be implemented
def logging_photo_page(request):
    if request.method != 'POST':
        return HttpResponse("[Error] logging_photo_page : It only permits POST messages")
    
    _baby = request.POST['baby']
    _date = request.POST['record_date']
    _photo_file = request.POST['photo_file']
    _gps_info = request.POST['gps_info']
    _voice_file = request.POST['voice_file']
    _memo = request.POST['memo']    
    
    try:
        babyInstance = Baby.objects.get(name = _baby)
    except ObjectDoesNotExist:
        return HttpResponse("[Error] logging_photo_page : The %s baby isn't exist! " % _baby)
    
    photo_log = PhotoHistory(baby = babyInstance, record_date = _date, photo_file = _photo_file, gps_info = _gps_info, voice_file = _voice_file, memo = _memo)
    photo_log.save()
        
    return HttpResponse("[Success] logging_photo_page : The %s baby's Photo Log is successfully inserted!" % _baby)   
